package controller;

import com.google.gson.Gson;
import pojo.Employees;
import pojo.Users;
import service.IStaffManagementService;
import service.ISystemManagementService;
import service.imppl.StaffManagementService;
import service.imppl.SystemManagementService;
import util.PageHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/employeeControl/*")
public class EmployeeController extends HttpServlet {
    private ISystemManagementService isy=new SystemManagementService();
    private IStaffManagementService isa=new StaffManagementService();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        int index = requestURI.lastIndexOf("/") + 1;
        String mName = requestURI.substring(index);
        if (mName.length() == 0) {
            mName = "showdt";
        }
        Class cla = this.getClass();
        Method method = null;
        try {
            request.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");
            method = cla.getMethod(mName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, request, response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        response.setContentType("application/json;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        boolean b=false;
        Users users=new Users();
        users.setUsername(username);
        ArrayList<Users> list=isy.queryUsers(users);
        String pwd=list.get(0).getPassword();
        if(pwd.equals(password)){
            b=true;
        }
        response.getWriter().println(new Gson().toJson(b));
    }
    public void employeeList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        request.setCharacterEncoding("utf-8");

        String eName = request.getParameter("ename");
        String ePosition = request.getParameter("eposition");
        String pageIndexStr = request.getParameter("pageIndex"); // 获取页码参数

        if (ePosition == null || "".equals(ePosition)) {
            ePosition = "-1";
        }
        Employees employees = new Employees();
        employees.seteName(eName);
        employees.setPositionId(Integer.parseInt(ePosition));
        PageHelper ph=new PageHelper();
        int i=isa.queryCountStaff(employees);
        ph.setDateCount(i);
        int indexInt=Integer.parseInt(request.getParameter("indexPage"));
        ph.setPageIndex(indexInt);
        ArrayList<Employees> employees1=isa.queryStaffs(employees,ph);
        ph.setListIndex(employees1);
        response.getWriter().println(new Gson().toJson(ph));
    }

    public void select(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        response.setContentType("application/json;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        String eId=request.getParameter("eId");
        Employees employees=isa.queryStaff(Integer.parseInt(eId));
        response.getWriter().println(new Gson().toJson(employees));
    }
    public void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        response.setContentType("application/json;charset=utf-8");
        request.setCharacterEncoding("utf-8");

        String eId = request.getParameter("eId");
        Employees employees = isa.queryStaff(Integer.parseInt(eId));

        // 安全处理参数
        String ageStr = request.getParameter("age");
        if (ageStr != null && !ageStr.trim().isEmpty()) {
            employees.setAge(Integer.parseInt(ageStr));
        }

        employees.seteName(request.getParameter("eName"));
        employees.setSex(request.getParameter("sex"));
        employees.setEmail(request.getParameter("email"));
        employees.setPhone(request.getParameter("phone"));

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        try {
            String birthStr = request.getParameter("birth");
            if (birthStr != null && !birthStr.trim().isEmpty()) {
                Date birth = formatter.parse(birthStr);
                employees.setBirth(birth);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        // 安全处理departmentId
        String deptIdStr = request.getParameter("departmentId");
        if (deptIdStr != null && !deptIdStr.trim().isEmpty()) {
            employees.setDepartmentId(Integer.parseInt(deptIdStr));
        }

        // 安全处理positionId
        String posIdStr = request.getParameter("positionId");
        if (posIdStr != null && !posIdStr.trim().isEmpty()) {
            employees.setPositionId(Integer.parseInt(posIdStr));
        }

        // 调用service更新
        boolean success = isa.changeStaff(employees);
        response.getWriter().println(new Gson().toJson(success));
    }
    public void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        response.setContentType("application/json;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        String eId=request.getParameter("eId");
        boolean b=isa.removeStaff(Integer.parseInt(eId));
        response.getWriter().println(new Gson().toJson(b));
    }
    public void insert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        response.setContentType("application/json;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        Employees employee = new Employees();
        String eName=request.getParameter("eName");
        String age=request.getParameter("age");
        String position=request.getParameter("position");
        String department=request.getParameter("department");
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        try {
            String hireDateStr=request.getParameter("hireDate");
            if (hireDateStr != null && !hireDateStr.trim().isEmpty()) {
                Date hireDate = formatter.parse(hireDateStr);
                employee.setHireDate(hireDate);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String salaryStr=request.getParameter("salary");
        String phone=request.getParameter("phone");
        String email=request.getParameter("email");

        employee.seteName(eName);
        employee.setAge(Integer.parseInt(age));
        employee.setPositionId(Integer.parseInt(position));
        employee.setDepartmentId(Integer.parseInt(department));
        try {
            double salary = Double.parseDouble(salaryStr);
            employee.setSalary(salary);
        } catch (NumberFormatException e) {
            System.out.println("字符串格式错误，无法转换为double");
        }
        employee.setPhone(phone);
        employee.setEmail(email);
        boolean b=isa.addStaff(employee);
        response.getWriter().println(new Gson().toJson(b));
    }
}
